package com.jingan.nursinghome.regulatory.select

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.support.design.internal.BaselineLayout
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.TextView
import cn.android.support.v7.lib.sin.crown.base.BaseActivity
import cn.android.support.v7.lib.sin.crown.base.BaseListenner
import cn.android.support.v7.lib.sin.crown.kotlin.anko.Titlebar
import cn.android.support.v7.lib.sin.crown.kotlin.base.BaseApplication
import cn.android.support.v7.lib.sin.crown.kotlin.base.BaseDialog
import cn.android.support.v7.lib.sin.crown.kotlin.bean.DateChoose
import cn.android.support.v7.lib.sin.crown.kotlin.common.Toast
import cn.android.support.v7.lib.sin.crown.kotlin.common.px
import cn.android.support.v7.lib.sin.crown.kotlin.dialog.DateChooseBetweenDialog
import cn.android.support.v7.lib.sin.crown.kotlin.dialog.RollerDialog
import cn.android.support.v7.lib.sin.crown.kotlin.popu.SpinnerPop
import cn.android.support.v7.lib.sin.crown.kotlin.utils.SelectorUtils
import cn.android.support.v7.lib.sin.crown.kotlin.widget.RoundTextView
import com.jingan.nursinghome.regulatory.data.MicrometerTable
import com.jingan.nursinghome.regulatory.dialog.LoginDialog
import com.jingan.nursinghome.regulatory.model.Qfinfo
import org.jetbrains.anko.*
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.swipeRefreshLayout
import com.jingan.nursinghome.regulatory.select.adapter.MyAdapter
import com.jingan.nursinghome.regulatory.select.adapter.MyAdapter2
import com.jingan.nursinghome.regulatory.view.H5
import kotlinx.coroutines.experimental.async
import java.util.ArrayList

/**
 * Created by 彭治铭 on 2018/7/15.
 */
class SelectHome(var activity: BaseActivity, var jlyID: String? = null, isStatus: Boolean = true, isTransparent: Boolean = true) : BaseDialog(activity, isStatus = isStatus, isTransparent = isTransparent) {

    private var exitTime: Long = 0

    init {
        isDarkmode(true)
//        isLocked(true) {
//            if (System.currentTimeMillis() - exitTime > 2000) {
//                Toast.show("再按一次退出")
//                exitTime = System.currentTimeMillis()
//            } else {
//                cn.android.support.v7.lib.sin.crown.base.BaseApplication.getInstance().exit()
//            }
//            System.gc()
//        }
        setWindowAnimations(cn.android.support.v7.lib.sin.crown.R.style.Crown_Window_right)
    }

    var date_start: TextView? = null//开始日期
    var date_end: TextView? = null//结束日期
    var dateChooseStart = DateChoose()
    var dateChooseEnd = DateChoose()
    val dateChooseBetweenDialog = DateChooseBetweenDialog(activity, dateChooseStart, dateChooseEnd)
    var swipeRefreshLayout: SwipeRefreshLayout? = null
    var recyclerView: RecyclerView? = null
    var btnNurs: TextView? = null
    var topBar: Titlebar.TopBar? = null
    var h5: H5? = null
    override fun onCreateView(context: Context): View? {

        var type = MicrometerTable.getInstance().getUser().utype
        if (type.equals("1")) {
            utype = UTYPE_3//测试
        } else if (type.equals("2")) {
            utype = UTYPE_2//千分表
        } else if (type.equals("3")) {
            utype = UTYPE_3//领导端
        }
        isH5 = false
        //Log.e("test","type:\t"+type+"\tutype:\t"+utype)

        return context.UI {
            verticalLayout {
                backgroundColor = Color.WHITE
                //第三个参数是返回键的颜色。此时是透明色。即返回键无效
                topBar = Titlebar.topBar(context as Activity, "领导端", Color.GRAY)
                topBar?.centerTextView?.apply {
                    textColor = Color.BLACK
                }
                topBar?.leftTextView?.onClick {
                    dismiss()
                }
                addView(topBar?.view)
                topBar?.shadow = false
                topBar?.rightTextView?.apply {
                    text = "登出"
                    textColor = Color.BLACK
                    onClick {
                        loginOrOut(false)
                    }
                    //lparams只能在anko布局里面使用
                    //实例对象不能使用lparams，所以只能使用layoutParams
                    layoutParams.apply {
                        width = wrapContent
                        height = wrapContent
                    }
                }
                linearLayout {
                    date_start = textView {
                        gravity = Gravity.CENTER
                        text = "开始时间"
                        background = null
                        SelectorUtils.selectorColor(this, "#D7D7D7", "#6699FF")
                        isSelected = true
                        textColor = Color.WHITE
                        textSize = px.textSizeX(32)
                        onClick {
                            isSelected = true
                            date_end?.isSelected = false
                            dateChooseBetweenDialog.star().show()
                        }
                    }.lparams {
                        width = 0
                        height = matchParent
                        weight = 1f
                    }
                    date_end = textView {
                        gravity = Gravity.CENTER
                        text = "结束时间"
                        background = null
                        SelectorUtils.selectorColor(this, "#D7D7D7", "#6699FF")
                        isSelected = false
                        textColor = Color.WHITE
                        textSize = px.textSizeX(32)
                        onClick {
                            isSelected = true
                            date_start?.isSelected = false
                            dateChooseBetweenDialog.end().show()
                        }
                    }.lparams {
                        width = 0
                        height = matchParent
                        weight = 1f
                    }
                }.lparams {
                    width = matchParent
                    height = px.x(100)
                }

                relativeLayout {
                    swipeRefreshLayout = swipeRefreshLayout {
                        setColorSchemeColors(Color.parseColor("#FF8080"), Color.parseColor("#FFFF00"), Color.parseColor("#00FF40"), Color.parseColor("#00FFFF"), Color.parseColor("#0080C0"))
                        setOnRefreshListener {
                            isRefreshing = true
                            refreshing()
                        }
                        recyclerView = recyclerView {
                            var linearLayoutManager = LinearLayoutManager(activity)
                            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
                            layoutManager = linearLayoutManager
                        }
                    }.lparams {
                        width = matchParent
                        height = matchParent
                    }

                    if (utype == UTYPE_3) {
                        //领导
                        recyclerView?.addItemDecoration(object : RecyclerView.ItemDecoration() {
                            override fun getItemOffsets(outRect: Rect?, itemPosition: Int, parent: RecyclerView?) {
                                super.getItemOffsets(outRect, itemPosition, parent)
                                outRect?.apply {
                                    top = 0
                                    bottom = 0
                                    if (itemPosition == 0) {
//                                        top = px.x(90)
                                        top = px.x(30)
                                    }
                                    models?.let {
                                        if (it.size ?: 0 > 1) {
                                            if (itemPosition == it.size - 1) {
                                                bottom = px.x(120)
                                            }
                                        }
                                    }
                                }
                            }
                        })

                        btnNurs = RoundTextView(context).apply {
                            backgroundColor = Color.WHITE
                            gravity = Gravity.CENTER
                            textColor = Color.BLACK
                            textSize = px.textSizeX(32)
                            text = "点击选择千分表巡检的敬老院"
                            strokeColor = Color.BLACK
                            strokeWidth = px.x(2f)
                            onClick {
                                rollerDialog?.show()
                                //Log.e("test", "敬老院显示:\t" + rollerDialog)
                                if (rollerDialog == null) {
                                    initJinnao()//重新初始化敬老院
                                    rollerDialog?.show()
                                    if (rollerDialog == null) {
                                        Toast.show("敬老院为空")
                                    }
                                }
                            }
                            visibility = View.INVISIBLE
                        }.lparams {
                            width = px.x(600)
                            height = px.x(70)
                            alignParentTop()
                            centerHorizontally()
                            topMargin = px.x(10)
                        }
                        addView(btnNurs)

                        h5 = H5(context).apply {
                            if (isH5) {
                                visibility = View.VISIBLE
                            } else {
                                visibility = View.INVISIBLE
                            }
                        }.lparams {
                            width = matchParent
                            height = matchParent
                            bottomMargin = px.x(100)
                        }
                        addView(h5)

                        textView {
                            backgroundColor = Color.parseColor("#66CCFF")
                            gravity = Gravity.CENTER
                            textColor = Color.WHITE
                            textSize = px.textSizeX(32)
                            if (isH5) {
                                text = "返回"
                            } else {
                                text = "整改项统计报表"
                            }

                            onClick {
                                isH5 = !isH5
                                if (isH5) {
                                    text = "返回"
                                    h5?.visibility = View.VISIBLE
                                    h5?.loadUrl(h5Url)
                                } else {
                                    text = "整改项统计报表"
                                    h5?.goBack()
                                    h5?.clearHistory()
                                    h5?.visibility = View.INVISIBLE

                                }
                            }
                        }.lparams {
                            width = matchParent
                            height = px.x(100)
                            alignParentBottom()
                        }
                    }


                }.lparams {
                    width = matchParent
                    height = matchParent
                }
            }
        }.view
    }

    //true登录，false退出登录
    private fun loginOrOut(login: Boolean) {
        LoginDialog.getInstance(activity, login, object : BaseListenner<Any?> {
            override fun onResult(result: Any?) {
                //登录成功回调

            }
        })
        dismiss()
    }

    companion object {
        var UTYPE_3 = 3//领导
        var UTYPE_2 = 2//千分表
        var utype = UTYPE_3
        var isH5 = false//是否显示H5页面
    }

    var adapter: RecyclerView.Adapter<*>? = null
    var models: MutableList<Qfinfo>? = null///数据
    //    var jlyID: String? = null//敬老院id
    var current = 3
    var allPotons = 4//查询全部的下标
    //巡机构选择
    var rollerDialog: RollerDialog? = null

    override fun listener() {
        //Log.e("test","初始化敬老院id:\t"+jlyID)
        async {
            if (utype == UTYPE_2) {
                topBar?.centerTextView?.setText("养老机构端")
            } else if (utype == UTYPE_3) {
                topBar?.centerTextView?.setText("区级端")
            }
            dateChooseBetweenDialog.isDarkmode(true)
            dateChooseBetweenDialog.dismiss()
            dateChooseBetweenDialog.setCallBack { dateChooseStart, dateChooseEnd ->
                if (dateChooseStart.toString().compareTo(dateChooseEnd.toString()) > 0) {
                    Toast.show("开始日期不能大于结束日期")
                } else {
                    date_start?.setText(dateChooseStart.toString())//开始时间
                    date_end?.setText(dateChooseEnd.toString())//结束时间
                    initData()
                }
            }
            models = mutableListOf<Qfinfo>()
            //jlyID = ""
            if (utype == UTYPE_2) {
                adapter = MyAdapter2(activity, models, jlyID)//千分表
            } else if (utype == UTYPE_3) {
                adapter = MyAdapter(activity, models, jlyID)//领导端
            }

            recyclerView?.adapter = adapter
            initData()
        }
    }


    //下拉刷新
    fun refreshing() {
        date_start?.setText("开始时间")
        date_end?.setText("结束时间")
        swipeRefreshLayout?.isRefreshing = true
        initData()
    }

    //初始化数据，或更新数据
    fun initData() {
        if (isH5) {
            h5?.visibility = View.VISIBLE
            h5?.goBack()
            //Log.e("test", "h5链接:\t" + h5Url)
            h5?.loadUrl(h5Url)
        } else {
            //Log.e("test","敬老院id:\t"+jlyID)
            KHttp.qfinfo(jlyID, getStratTime(), getEndTime(), activity) {
                models?.clear()
                models?.addAll(it)
                adapter?.notifyDataSetChanged()
                swipeRefreshLayout?.isRefreshing = false
            }
        }
        initJinnao()
    }

    var h5Url: String? = null
        get() {
//            if(SelectMain.ismic.equals("1")){
//                return ""//千分表报表暂时屏蔽
//            }
            if (SelectMain.ismic.equals("1")) {
                //千分表
                return "http://120.76.45.102:8080/yanglaoapp/jinganappecharts/qfb.html?starttime=" + getStratTime() + "&endtime=" + getEndTime() + "&ismic=" + SelectMain.ismic
                //自己的服务器
                //return "http://new.rflinker.com/jinganappecharts/qfb.html?starttime=" + getStratTime() + "&endtime=" + getEndTime() + "&ismic=" + SelectMain.ismic
            } else {
                //日常表
                return "http://120.76.45.102:8080/yanglaoapp/jinganappecharts/index.html?starttime=" + getStratTime() + "&endtime=" + getEndTime() + "&ismic=" + SelectMain.ismic
                //自己服务器
                //return "http://new.rflinker.com/jinganappecharts/index.html?starttime=" + getStratTime() + "&endtime=" + getEndTime() + "&ismic=" + SelectMain.ismic
            }
        }

    fun getStratTime(): String? {
        var starttime: String? = date_start?.text.toString()
        starttime?.let {
            if (it.trim().equals("开始时间") || it.trim().equals("")) {
                starttime = "2010-01-01"
            }
        }
        return starttime
    }

    fun getEndTime(): String? {
        var endtime: String? = date_end?.text.toString()
        endtime?.let {
            if (it.trim().equals("结束时间") || it.trim().equals("")) {
                endtime = "2100-01-01"
            }
        }
        return endtime
    }

    //初始化敬老院
    fun initJinnao() {
        if (rollerDialog == null) {
            //敬老院集合
            val items = ArrayList<String>()
            for (i in 0 until MicrometerTable.getInstance().jlys.size) {
                if (MicrometerTable.getInstance().jlys != null && MicrometerTable.getInstance().jlys[i] != null) {
                    items.add(MicrometerTable.getInstance().jlys[i].name)
                }
            }
            if (items.size > 0) {
                if (items.size < allPotons) {
                    allPotons = items.size - 1
                }
                items.add(allPotons, "全部")
                current = allPotons
            }
            //Log.e("test", "敬老院数量:\t" + items.size)
            if (items.size <= 0) {
                for (i in 0 until MicrometerTable.getInstance().jlys.size) {
                    items.add(MicrometerTable.getInstance().jlys[i].name)
                }
                if (items.size < allPotons) {
                    allPotons = items.size - 1
                }
                items.add(allPotons, "全部")
                current = allPotons
            }
            rollerDialog = RollerDialog(activity, true, true)
            rollerDialog?.rollerView?.isCyclic = false
            rollerDialog?.rollerView?.setCount(7)
            rollerDialog?.info?.setText("请选择巡检敬老院")
            rollerDialog?.setItems(items)
            rollerDialog?.setCurrentPostion(current)
            rollerDialog?.isDarkmode(true)
            rollerDialog?.setItemSelectListener { item, position ->
                btnNurs?.setText(item)
                if (position == allPotons) {
                    //查询全部
                    jlyID = null
                } else {
                    current = position
                    jlyID = MicrometerTable.getInstance().getJlyID(item)
                }
                initData()
            }
            rollerDialog?.dismiss()
        }
    }

    override fun recycleView() {
    }


}